package com.woniuxy.kaer.tenants.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.kaer.commons.util.*;
import com.woniuxy.kaer.service.feign.ServiceFeignClient;
import com.woniuxy.kaer.tenants.dto.ShopDto;
import com.woniuxy.kaer.tenants.dto.ShopInfoDto;
import com.woniuxy.kaer.tenants.dto.ShopServiceDto;
import com.woniuxy.kaer.tenants.entity.ApplyAttachments;
import com.woniuxy.kaer.tenants.entity.Founder;
import com.woniuxy.kaer.tenants.entity.Settled;
import com.woniuxy.kaer.tenants.entity.ShopInfo;
import com.woniuxy.kaer.tenants.mapper.ApplyAttachmentsMapper;
import com.woniuxy.kaer.tenants.mapper.FounderMapper;
import com.woniuxy.kaer.tenants.mapper.SettledMapper;
import com.woniuxy.kaer.tenants.mapper.ShopInfoMapper;
import com.woniuxy.kaer.tenants.param.*;
import com.woniuxy.kaer.tenants.service.ShopInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年2月17日
 */
@Service
public class ShopInfoServiceImpl extends ServiceImpl<ShopInfoMapper, ShopInfo> implements ShopInfoService {
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private FounderMapper founderMapper;
    @Resource
    private SettledMapper settledMapper;
    @Resource
    private ServiceFeignClient serviceFeignClient;
    @Resource
    private OSSUtil ossUtil;
    @Override
    public void refineTenantsInfo(RefineTenantsInfoParam param) throws Exception {
        Founder founder = founderMapper.selectById(param.getFounderId());
        if(null==founder){
            throw new Exception("商家不存在");
        }
        if(founder.getFounderState()!=Data.FOUNDER_STATE_NORMAL){
            throw new Exception("商家状态异常");
        }
        founder.setFounderState(Data.FOUNDER_STATE_DISABLE);
        founderMapper.updateById(founder);
        QueryWrapper<Settled> settledQueryWrapper = new QueryWrapper<>();
        settledQueryWrapper.eq("founder_id",param.getFounderId());
        List<Settled> settleds = settledMapper.selectList(settledQueryWrapper);
        for (Settled settled : settleds) {
            if(settled.getSettledState()==Data.SETTLED_STATE_PASS){
                ShopInfo shopInfo = BeanUtil.toBean(param, ShopInfo.class);
                byte[] bytes = new byte[4];
                param.getShopLogo().getInputStream().read(bytes);
                if(!(ossUtil.isJpg(bytes)||ossUtil.isPng(bytes))){
                    throw new Exception("文件格式不正确");
                }

                String s = FileUtil.extName(param.getShopLogo().getOriginalFilename());
                String s1 = UUID.randomUUID().toString();
                String shopLogo = ossUtil.uploadFile(param.getShopLogo().getInputStream(), s1 + "." + s, "guojiandong");
                shopInfo.setShopLogo(shopLogo);
                shopInfo.setFirstTime(LocalDateTime.now());
                shopInfo.setShopState(Data.SHOP_INFO_STATE_NORMAL);
                shopInfo.setServiceCount(0);
                shopInfo.setShopScore(0.0);
                shopInfoMapper.insert(shopInfo);
            }
        }
    }

    @Override
    public ShopInfoDto getShopInfoByShopId(Integer shopId) throws Exception {
        ShopInfo shopInfo = shopInfoMapper.selectById(shopId);
        if(null==shopInfo){
            throw new Exception("商家不存在");
        }
        if(shopInfo.getShopState()!=Data.SHOP_INFO_STATE_NORMAL){
            throw new Exception("商家状态异常");
        }
        ShopInfoDto shopInfoDto = BeanUtil.toBean(shopInfo, ShopInfoDto.class);
        return shopInfoDto;
    }

    @Override
    public void updateShopScore(UpdateShopScoreParam param) throws Exception {
        ShopInfo shopInfo = shopInfoMapper.selectById(param.getShopId());
        if (null==shopInfo){
            throw new Exception("商家不存在");
        }
        if(shopInfo.getShopState()!=Data.SHOP_INFO_STATE_NORMAL){
            throw new Exception("商家状态异常");
        }
        shopInfo.setServiceCount(shopInfo.getServiceCount()+1);
        shopInfo.setShopScore(param.getShopScore());
        shopInfoMapper.updateById(shopInfo);
    }

    @Override
    public List<ShopDto> selectShopByServiceName(SelectShopByServiceNameParam param) throws Exception {
        Result<List<Integer>> result = serviceFeignClient.getServiceBaseByServiceName(param.getServiceName());
        List<Integer> shopIds = result.getData();
        //通过商铺名字关键子查询商户
        List<String> Keys = IKAnalyzerUtil.analyze(param.getServiceName());
        if(null!=Keys){
            for (String key : Keys) {
                QueryWrapper<ShopInfo> shopInfoQueryWrapper = new QueryWrapper<>();
                shopInfoQueryWrapper.or().like("shop_name",key);
                List<ShopInfo> shopInfos = shopInfoMapper.selectList(shopInfoQueryWrapper);
                for (ShopInfo shopInfo : shopInfos) {
                    if(!shopIds.contains(shopInfo.getShopId())){
                        shopIds.add(shopInfo.getShopId());
                    }
                }
            }
        }
        ArrayList<ShopInfo> shopInfos = new ArrayList<ShopInfo>();
        for (Integer shopId : shopIds) {
            ShopInfo shopInfo = shopInfoMapper.selectById(shopId);
            if(null!=shopInfo){
                shopInfos.add(shopInfo);
            }
        }
        ArrayList<ShopDto> shopDtos = new ArrayList<>();
        for (ShopInfo shopInfo : shopInfos) {
            ShopDto shopDto = BeanUtil.toBean(shopInfo, ShopDto.class);
            /**
             * 计算两地之间的距离
             * @param lat1 第一点的纬度
             * @param lon1 第一点的经度
             * @param lat2 第二点的纬度
             * @param lon2 第二点的经度
             * @return 两地之间的距离，单位：千米
             */
            double distance1 = DistanceCalculator.calculateDistance(param.getUserLatitude(), param.getUserLongitude(), shopDto.getShopLatitude(), shopDto.getShopLongitude());
            //取地址两位小数
            BigDecimal bd = new BigDecimal(distance1);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            double distance = bd.doubleValue();
            shopDto.setDistance(distance);
            shopDtos.add(shopDto);
        }

        List<ShopDto> sortedShopDtos = shopDtos.stream()
                .sorted(Comparator.comparingDouble(ShopDto::getDistance))
                .collect(Collectors.toList());
        return sortedShopDtos;
    }

    @Override
    public ShopInfoDto getShopInfoByFounderId(Integer founderId) throws Exception {
        QueryWrapper<ShopInfo> shopInfoQueryWrapper = new QueryWrapper<>();
        shopInfoQueryWrapper.eq("founder_id",founderId);
        ShopInfo shopInfo = shopInfoMapper.selectOne(shopInfoQueryWrapper);
        if(null==shopInfo){
            throw new Exception("商家不存在");
        }
        ShopInfoDto shopInfoDto = BeanUtil.toBean(shopInfo, ShopInfoDto.class);
        return shopInfoDto;
    }

    @Override
    public List<ShopInfoDto> getAllShopInfo() throws Exception {
        List<ShopInfo> shopInfos = shopInfoMapper.selectList(null);
        if(null==shopInfos&&shopInfos.size()==0){
            throw new Exception("商家不存在");
        }
        ArrayList<ShopInfoDto> shopInfoDtos = new ArrayList<>();
        for (ShopInfo shopInfo : shopInfos) {
            ShopInfoDto shopInfoDto = BeanUtil.toBean(shopInfo, ShopInfoDto.class);
            shopInfoDtos.add(shopInfoDto);
        }
        return shopInfoDtos;
    }

    @Override
    public void shopServiceCount(ChangeShopScoreParam param) throws Exception {
        System.out.println(param.getShopId());
        ShopInfo shopInfo = shopInfoMapper.selectById(param.getShopId());
        if (null==shopInfo){
            throw new Exception("商家不存在");
        }
        shopInfo.setServiceCount(shopInfo.getServiceCount());
        shopInfo.setShopScore(param.getShopScore());
        shopInfoMapper.updateById(shopInfo);
    }

    @Override
    public List<ShopServiceDto> getShopInfoByShopName(GetShopServiceParam getShopServiceParam) {
        ArrayList<ShopServiceDto> shopServiceDtos = new ArrayList<>();
        List<String> keys = IKAnalyzerUtil.analyze(getShopServiceParam.getShopName());
        for (String key : keys) {
            QueryWrapper<ShopInfo> shopInfoQueryWrapper = new QueryWrapper<>();
            shopInfoQueryWrapper.like("shop_name",key);
            ShopInfo shopInfo = shopInfoMapper.selectOne(shopInfoQueryWrapper);
            ShopServiceDto shopServiceDto = BeanUtil.toBean(shopInfo, ShopServiceDto.class);
            /**
             * 计算两地之间的距离
             * @param lat1 第一点的纬度
             * @param lon1 第一点的经度
             * @param lat2 第二点的纬度
             * @param lon2 第二点的经度
             * @return 两地之间的距离，单位：千米
             */
            double distance1 = DistanceCalculator.calculateDistance(getShopServiceParam.getUserLatitude(), getShopServiceParam.getUserLongitude(), shopInfo.getShopLatitude(), shopInfo.getShopLongitude());
            //取地址两位小数
            BigDecimal bd = new BigDecimal(distance1);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            double distance = bd.doubleValue();
            shopServiceDto.setDistance(distance);
            shopServiceDtos.add(shopServiceDto);
        }
        return shopServiceDtos;
    }
}
